package org.net5ijy.security.util;

import java.io.IOException;

import org.springframework.core.io.support.ResourcePropertySource;

/**
 * ApplicationSourceUtil
 *
 * @author XGF
 * @date 2020/11/30 22:49
 */
public class ApplicationSourceUtil {

  public static final String APPLICATION_PROPERTIES_NAME = "application";

  public static final String APPLICATION_PROPERTIES = "classpath:application.properties";

  private static ResourcePropertySource source;

  private static ApplicationSourceUtil util = new ApplicationSourceUtil();

  private ApplicationSourceUtil() {
    try {
      source =
          new ResourcePropertySource(APPLICATION_PROPERTIES_NAME, APPLICATION_PROPERTIES);
    } catch (IOException e) {
      throw new RuntimeException("无法加载配置文件: " + APPLICATION_PROPERTIES);
    }
  }

  public static ApplicationSourceUtil getApplicationSourceUtil() {
    return util;
  }

  public String getString(String key, String def) {
    Object value = source.getProperty(key);
    return value == null ? def : value.toString().trim();
  }

  public Integer getInteger(String key, Integer def) {
    Object value = source.getProperty(key);
    if (value == null) {
      return def;
    }
    try {
      return Integer.parseInt(value.toString().trim());
    } catch (NumberFormatException e) {
      return def;
    }
  }
}
